class Asset < ActiveRecord::Base
  attr_accessor :hashed_timestamp_and_random_number
  has_attachment :storage => :file_system, :path_prefix => 'public/assets', :size => 0..1024.megabytes
  validates_as_attachment

  def after_save
    if self.path.blank? and !@hashed_timestamp_and_random_number.blank?
      self.path = File.join(attachment_options[:path_prefix].to_s, generate_subfolder(@hashed_timestamp_and_random_number), generate_filename(@hashed_timestamp_and_random_number))
      save
    end
    if self.uri.blank? and !@hashed_timestamp_and_random_number.blank?
      self.uri = File.join('/assets', generate_subfolder(@hashed_timestamp_and_random_number), generate_filename(@hashed_timestamp_and_random_number))
      save
    end
  end

  def before_destroy
    File.delete File.join(RAILS_ROOT, self.path) if File.exist?(File.join(RAILS_ROOT, self.path))
  end

  def full_filename(thumbnail = nil)
    @hashed_timestamp_and_random_number ||= Digest::MD5.hexdigest(Time.now.to_s + rand(10000).to_s)
    file_system_path = (thumbnail ? thumbnail_class : self).attachment_options[:path_prefix].to_s
    File.join(RAILS_ROOT, file_system_path, generate_subfolder(@hashed_timestamp_and_random_number), generate_filename(@hashed_timestamp_and_random_number))
  end

  def generate_subfolder hashed_timestamp_and_random_number
    hashed_timestamp_and_random_number[0..1]
  end

  def generate_filename hashed_timestamp_and_random_number
    "#{hashed_timestamp_and_random_number}#{filename.scan(/\.\w+$/)}"
  end

  def to_label
    filename
  end
end